package com.example.springbootapi.service.impl;

import com.example.springbootapi.entity.UserAddress;
import com.example.springbootapi.dto.UserAddressDTO;
import com.example.springbootapi.vo.UserAddressVO;
import com.example.springbootapi.mapper.UserAddressMapper;
import com.example.springbootapi.service.UserAddressService;
import com.example.springbootapi.common.PageResult;
import com.example.springbootapi.common.BusinessException;
import com.example.springbootapi.common.ErrorCode;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户收货地址表（关联用户，支持多地址） 服务实现类
 * 
 * @author 开发者
 * @version 1.0.0
 * @since 2025-10-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Override
    public PageResult<UserAddressVO> page(Integer pageNum, Integer pageSize, UserAddressDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        
        // 动态查询条件构建
        if (queryDTO != null) {
            // 关联用户ID（外键：user.id）查询条件
            if (StringUtils.hasText(queryDTO.getUserId())) {
                queryWrapper.eq(UserAddress::getUserId, queryDTO.getUserId());
            }
            // 收货人姓名查询条件
            if (StringUtils.hasText(queryDTO.getReceiverName())) {
                queryWrapper.like(UserAddress::getReceiverName, queryDTO.getReceiverName());
            }
            // 收货人手机号查询条件
            if (StringUtils.hasText(queryDTO.getReceiverPhone())) {
                queryWrapper.like(UserAddress::getReceiverPhone, queryDTO.getReceiverPhone());
            }
            // 省份（如&quot;广东省&quot;）查询条件
            if (StringUtils.hasText(queryDTO.getProvince())) {
                queryWrapper.like(UserAddress::getProvince, queryDTO.getProvince());
            }
            // 城市（如&quot;深圳市&quot;）查询条件
            if (StringUtils.hasText(queryDTO.getCity())) {
                queryWrapper.like(UserAddress::getCity, queryDTO.getCity());
            }
            // 区县（如&quot;南山区&quot;）查询条件
            if (StringUtils.hasText(queryDTO.getDistrict())) {
                queryWrapper.like(UserAddress::getDistrict, queryDTO.getDistrict());
            }
            // 详细地址（如&quot;XX街道XX小区1栋101&quot;）查询条件
            if (StringUtils.hasText(queryDTO.getDetailAddress())) {
                queryWrapper.like(UserAddress::getDetailAddress, queryDTO.getDetailAddress());
            }
            // 是否默认地址（1&#x3D;是，0&#x3D;否，一个用户仅1个默认地址）查询条件
            if (queryDTO.getIsDefault() != null) {
                queryWrapper.eq(UserAddress::getIsDefault, queryDTO.getIsDefault());
            }
            // 逻辑删除（0&#x3D;未删除，1&#x3D;已删除）查询条件
            if (StringUtils.hasText(queryDTO.getIsDeleted())) {
                queryWrapper.eq(UserAddress::getIsDeleted, queryDTO.getIsDeleted());
            }
            // 创建时间查询条件
            if (queryDTO.getCreateTime() != null) {
                queryWrapper.eq(UserAddress::getCreateTime, queryDTO.getCreateTime());
            }
            // 更新时间查询条件
            if (queryDTO.getUpdateTime() != null) {
                queryWrapper.eq(UserAddress::getUpdateTime, queryDTO.getUpdateTime());
            }
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc(UserAddress::getCreateTime);
        
        // 分页查询
        IPage<UserAddress> page = new Page<>(pageNum, pageSize);
        IPage<UserAddress> result = this.page(page, queryWrapper);
        
        // 转换为VO
        List<UserAddressVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.<UserAddressVO>builder()
                .records(voList)
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();
    }

    @Override
    public UserAddressVO getById(Long id) {
        UserAddress entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户收货地址表（关联用户，支持多地址）不存在");
        }
        return convertToVO(entity);
    }

    @Override
    public UserAddressVO create(UserAddressDTO DTO) {
        // 参数验证
        validateDTO(DTO);
        
        // 转换为实体
        UserAddress entity = convertToEntity(DTO);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.save(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "创建用户收货地址表（关联用户，支持多地址）失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public UserAddressVO update(Long id, UserAddressDTO DTO) {
        // 检查记录是否存在
        UserAddress existingEntity = this.getById(id);
        if (existingEntity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户收货地址表（关联用户，支持多地址）不存在");
        }
        
        // 参数验证
        validateDTO(DTO);
        
        // 更新实体
        UserAddress entity = convertToEntity(DTO);
        entity.setId(id);
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.updateById(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "更新用户收货地址表（关联用户，支持多地址）失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public void delete(Long id) {
        // 检查记录是否存在
        UserAddress entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户收货地址表（关联用户，支持多地址）不存在");
        }
        
        // 删除
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "删除用户收货地址表（关联用户，支持多地址）失败");
        }
    }

    @Override
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "删除ID列表不能为空");
        }
        
        // 批量删除
        boolean success = this.removeByIds(ids);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "批量删除用户收货地址表（关联用户，支持多地址）失败");
        }
    }

    // 关联关系查询方法将在后续版本中支持

    /**
     * 实体转VO
     */
    private UserAddressVO convertToVO(UserAddress entity) {
        if (entity == null) {
            return null;
        }
        
        UserAddressVO vo = new UserAddressVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    /**
     * DTO转实体
     */
    private UserAddress convertToEntity(UserAddressDTO dto) {
        if (dto == null) {
            return null;
        }
        
        UserAddress entity = new UserAddress;
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 验证DTO参数
     */
    private void validateDTO(UserAddressDTO dto) {
        if (dto == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "用户收货地址表（关联用户，支持多地址）信息不能为空");
        }
        
        // 必填字段验证
        if (!StringUtils.hasText(dto.getUserId())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "关联用户ID（外键：user.id）不能为空");
        }
        if (!StringUtils.hasText(dto.getReceiverName())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "收货人姓名不能为空");
        }
        if (!StringUtils.hasText(dto.getReceiverPhone())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "收货人手机号不能为空");
        }
        if (!StringUtils.hasText(dto.getProvince())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "省份（如&quot;广东省&quot;）不能为空");
        }
        if (!StringUtils.hasText(dto.getCity())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "城市（如&quot;深圳市&quot;）不能为空");
        }
        if (!StringUtils.hasText(dto.getDistrict())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "区县（如&quot;南山区&quot;）不能为空");
        }
        if (!StringUtils.hasText(dto.getDetailAddress())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "详细地址（如&quot;XX街道XX小区1栋101&quot;）不能为空");
        }
    }
}
